<template>
  <div
    v-if="!isEmpty(salesmansData)"
    class="page-wrapper"
    v-loading="loading"
    :element-loading-text="`解析中...${parseNum ? `已解析${parseNum}/${parseTotal}` : ''}`"
  >
    <div class="mb-10">
      <el-alert type="warning" :closable="false">
        <template #default>
          从飞书导入{{ salesmansData.nickName }} ({{ salesmansData.phonenumber }})
          的个人客户信息。注意：请严格按照模板信息中的数据处理，不要修改模板中的表头文字！！！
        </template>
      </el-alert>
    </div>

    <div class="mb-20 card-box">
      <div style="margin-bottom: 10px">
        <el-space alignment="flex-end">
          <el-upload
            :show-file-list="false"
            accept=".xlsx,.xls"
            :on-change="startLoading"
            :before-upload="onLocalImport"
          >
            <el-button type="success">数据导入（本地）</el-button>
          </el-upload>

          <el-button type="primary" @click="openImportDialog" :disabled="tableData.length === 0">
            批量导入
          </el-button>
        </el-space>
      </div>
      <data-table
        :data="tableData"
        :total="tableData.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
      />
    </div>
    <import-progress-dialog
      ref="importProgressRef"
      :salesmansId="userApp.id"
      :salesmansData="salesmansData"
      :data="tableData"
    />
  </div>
  <div v-else class="authNo">
    <img :src="accountNo" alt="" srcset="" />
    <span>当前帐号无法使用该模块，请使用销售人员账号登陆 </span>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import DataTable from './components/dataTable.vue';
import ImportProgressDialog from './components/importProgressDialog.vue';
import { readExcel } from '@/utils/excel';
import { useYw } from '../../../hooks/useYw';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getValueByLabel, salesSearchOptions } from '../../../filterOptions/options';
import useUserStore from '../../../store/modules/user';
import { isEmpty } from 'lodash';
import accountNo from '../../../assets/images/accountNo.png';
import { parseInfo } from '../../../utils';

const { ywList } = useYw();
const userApp = useUserStore();

const importProgressRef = ref();
// loading 状态
const loading = ref(false);
// 业务员选项
const salesmans = computed(() => {
  if (!ywList.value) return [];
  return ywList.value.map((v: any) => ({ label: v.nickName, value: v.userId, ...v }));
});

// 根据登录信息返回业务员的信息
const salesmansData = computed(() => {
  if (userApp.id) {
    return salesmans.value.find((v) => v.value === userApp.id);
  }
  return {};
});

// 页面数据
const tableData = ref<any[]>([]);
const pageSize = 50;
const currentPage = ref(1);
const parseNum = ref(0);
const parseTotal = ref(0);
const mapKeys = (data: any) => {
  try {
    const {
      customerInfo,
      isAddWechat,
      category,
      isAddedWeChat,
      orderCategory,
      remark1,
      remark2,
      remark3
    } = JSON.parse(data['信息']);
    const userData = parseInfo(customerInfo);
    return {
      ...userData,
      isAddWechat,
      category,
      isAddedWeChat,
      orderCategory,
      remark1,
      remark2,
      remark3
    };
  } catch (error) {
    console.log('error ==> ', error);
    return data;
  }
};

const startLoading = () => {
  loading.value = true;
};

// 本地解析 Excel
const onLocalImport = async (file: File) => {
  const tableDataParse: any[] = [];
  try {
    const excelData = await readExcel(file);
    if (!excelData || !Array.isArray(excelData)) {
      throw new Error('Excel 数据格式异常');
    }
    parseTotal.value = excelData.length;
    for (let i = 0; i < excelData.length; i++) {
      const row = excelData[i];
      parseNum.value = i + 1;
      const deep = mapKeys(row);
      console.log('deep ====> ', deep);
      tableDataParse.push(deep);
      // 让 UI 有机会渲染
      await new Promise((resolve) => setTimeout(resolve, 5));
    }
    ElMessage.success('解析完成');
    tableData.value = tableDataParse;
  } catch (err: any) {
    console.error('Excel 解析失败：', err);
    ElMessage.error(err?.message || 'Excel 解析失败，请检查文件格式是否正确');
  } finally {
    parseNum.value = 0;
    parseTotal.value = 0;
    loading.value = false;
  }
  return false;
};

//
const openImportDialog = () => {
  if (!userApp.id) {
    return ElMessage.warning('业务员信息错误');
  }

  ElMessageBox.confirm('确定要导入数据吗？此操作不可逆。', '导入确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击了“确定”
    importProgressRef.value.show();
  });
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  padding: 20px;
}

.card-box .nickname {
  font-weight: 600;
  color: #1890ff; /* 蓝色突出账号名 */
}

.card-box .phone {
  color: #666;
  font-family: 'Courier New', monospace; /* 手机号用等宽字体更清晰 */
}

.mt-20 {
  margin-top: 20px;
}

.progress-bar {
  background: #f4f8ff;
  border-left: 4px solid #409eff;
  padding: 8px 12px;
  margin-bottom: 10px;
  border-radius: 4px;
}

.authNo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;

  img {
    width: 300px;
  }

  span {
    margin-top: 50px;
    font-size: 20px;
    border: none;
    border-radius: 5px;
    color: #7d7d7d;
    font-weight: 500;
  }
}
</style>
